import React, { Component } from "react";
import {
    Table,
    Tag,
    Form,
    Button,
    Input,
    Collapse,
    Pagination,
    Divider,
    message,
    Select,
} from "antd";
import { tableList, deleteItem, editItem } from "../../api/advice";
import EditForm from "./forms/editForm";
const { Column } = Table;
const { Panel } = Collapse;
class TableComponent extends Component {
    _isMounted = false; // 这个变量是用来标志当前组件是否挂载
    state = {
        list: [],
        loading: false,
        total: 0,
        listQuery: {
            pageNumber: 1,
            pageSize: 10,
            title: "",
            status: "",
            author: "",
        },
        editModalVisible: false,
        editModalLoading: false,
        currentRowData: {
            id: 0,
            author: "",
            title: "",
            date: "",
            status: "unread",
        },
    };
    fetchData = () => {
        this.setState({ loading: true });
        tableList().then((response) => {
            this.setState({ loading: false });
            // console.log(response.data);
            let myList = response;
            // for (var i = 0; i < myList.length-1; i++) { // 对收到的数据进行冒泡排序
            //     for (var j = 0; j < myList.length-i-1; j++) {
            //          // 相邻元素两两对比，元素交换，大的元素交换到后面
            //         if (myList[j].suggestionId > myList[j + 1].suggestionId) {
            //             var temp = myList[j];
            //             myList[j] = myList[j+1];
            //             myList[j+1] = temp;
            //         }
            //     }
            // }
            // 调整时间格式
            for (let l = 0; l < myList.length; l++) {
                let timeObj = new Date(parseInt(myList[l].suggestionTime));
                let year = timeObj.getFullYear();
                let month = timeObj.getMonth() + 1;
                let date = timeObj.getDate();
                let timeStr = year + "年" + month + "月" + date + "日";
                myList[l].suggestionTime = timeStr;
            }
            // 筛选条件
            let flagS =
                this.state.listQuery.status == "read" || this.state.listQuery.status == "unread"
                    ? 1
                    : 0;
            let flagA = this.state.listQuery.author != "" ? 1 : 0;
            let resList = [];
            if (flagA && flagS) {
                //均有筛选条件，即id和状态双重筛选
                let tempList = myList;
                resList = tempList.filter((obj) => {
                    //筛选出来id相同的
                    // console.log("obj",obj)
                    return obj.userId == this.state.listQuery.author;
                });
                resList = resList.filter((obj) => {
                    //筛选出来status相同的
                    // console.log("obj",obj)
                    return obj.suggestionStatus == this.state.listQuery.status;
                });
                console.log("resList:", resList);
            } else if (flagA) {
                //flagA非空，即筛选用户id相同的
                let tempList = myList;
                resList = tempList.filter((obj) => {
                    //筛选出来id相同的
                    // console.log("obj",obj)
                    return obj.userId == this.state.listQuery.author;
                });
            } else if (flagS) {
                //flagS非空，即筛选状态相同的
                let tempList = myList;
                resList = tempList.filter((obj) => {
                    //筛选出来status相同的
                    // console.log("obj",obj)
                    return obj.suggestionStatus == this.state.listQuery.status;
                });
            } else {
                resList = myList;
            }

            const list = resList;
            const total = list.length; //********************///////edit */
            if (this._isMounted) {
                this.setState({ list, total });
            }
        });
    };
    componentDidMount() {
        this._isMounted = true;
        this.fetchData();
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    filterIDChange = (e) => {
        let value = e.target.value;
        this.setState((state) => ({
            listQuery: {
                ...state.listQuery,
                author: value,
            },
        }));
    };
    filterStatusChange = (value) => {
        this.setState((state) => ({
            listQuery: {
                ...state.listQuery,
                status: value,
            },
        }));
    };

    handleDelete = (row) => {
        deleteItem({ id: row.suggestionId }).then((res) => {
            message.success("删除成功");
            this.fetchData();
        });
    };
    handleEdit = (row) => {
        this.setState({
            currentRowData: Object.assign({}, row),
            editModalVisible: true,
        });
    };

    handleOk = (_) => {
        const { form } = this.formRef.props;
        form.validateFields((err, fieldsValue) => {
            if (err) {
                return;
            }
            const values = {
                ...fieldsValue,
                date: fieldsValue["date"].format("YYYY-MM-DD HH:mm:ss"),
            };
            this.setState({ editModalLoading: true });
            editItem(values)
                .then((response) => {
                    form.resetFields();
                    this.setState({ editModalVisible: false, editModalLoading: false });
                    message.success("编辑成功!");
                    this.fetchData();
                })
                .catch((e) => {
                    message.success("编辑失败,请重试!");
                });
        });
    };

    handleCancel = (_) => {
        this.setState({
            editModalVisible: false,
        });
    };
    render() {
        return (
            <div className="app-container">
                <Collapse defaultActiveKey={["1"]}>
                    <Panel header="筛选" key="1">
                        <Form layout="inline">
                            <Form.Item label="用户ID:">
                                <Input onChange={this.filterIDChange} />
                            </Form.Item>
                            <Form.Item label="状态:">
                                <Select style={{ width: 120 }} onChange={this.filterStatusChange}>
                                    <Select.Option value="read">read</Select.Option>
                                    <Select.Option value="unread">unread</Select.Option>
                                    <Select.Option value="all">all</Select.Option>
                                </Select>
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" icon="search" onClick={this.fetchData}>
                                    搜索
                                </Button>
                            </Form.Item>
                        </Form>
                    </Panel>
                </Collapse>
                <br />
                <Table
                    bordered
                    rowKey={(record, index) => record.suggestionId}
                    dataSource={this.state.list}
                    loading={this.state.loading}
                    pagination={{
                        total: this.state.total,
                        showTotal: (total) => `共${total}条数据`,
                    }}
                >
                    <Column
                        title="序号"
                        dataIndex="suggestionId"
                        key="suggestionId"
                        width={100}
                        align="center"
                        sorter={(a, b) => a.suggestionId - b.suggestionId}
                        defaultSortOrder="descend"
                    />
                    <Column
                        title="用户ID"
                        dataIndex="userId"
                        key="userId"
                        width={100}
                        align="center"
                    />
                    <Column
                        title="意见内容"
                        dataIndex="suggestionContent"
                        key="suggestionContent"
                        width={200}
                        align="center"
                    />
                    <Column
                        title="状态"
                        dataIndex="suggestionStatus"
                        key="suggestionStatus"
                        width={100}
                        align="center"
                        render={(status) => {
                            if (status === "") {
                                status = "unread";
                            }
                            let color =
                                status === "read" ? "green" : status === "unread" ? "red" : "";
                            return (
                                <Tag color={color} key={status}>
                                    {status}
                                </Tag>
                            );
                        }}
                    />
                    <Column
                        title="时间"
                        dataIndex="suggestionTime"
                        key="date"
                        width={195}
                        align="center"
                    />
                    <Column
                        title="操作"
                        key="action"
                        width={160}
                        align="center"
                        render={(text, row) => (
                            <span>
                                <Button
                                    type="primary"
                                    shape="circle"
                                    icon="edit"
                                    title="编辑"
                                    onClick={this.handleEdit.bind(null, row)}
                                />
                                <Divider type="vertical" />
                                <Button
                                    type="primary"
                                    shape="circle"
                                    icon="delete"
                                    title="删除"
                                    onClick={this.handleDelete.bind(null, row)}
                                />
                            </span>
                        )}
                    />
                </Table>
                <br />
                <EditForm
                    currentRowData={this.state.currentRowData}
                    wrappedComponentRef={(formRef) => (this.formRef = formRef)}
                    visible={this.state.editModalVisible}
                    confirmLoading={this.state.editModalLoading}
                    onCancel={this.handleCancel}
                    onOk={this.handleOk}
                />
            </div>
        );
    }
}

export default TableComponent;
